<template>
	<tm-app ref="app">
		<tm-form v-if="showflag" @submit="confirm" v-model="entity" ref="form" :label-width="190">
			<tm-form-item required label="name" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.name" :transprent="true" :showBottomBotder="false"
					placeholder="name"></tm-input>
			</tm-form-item>
			<tm-form-item required label="phone" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.phone" :transprent="true" :showBottomBotder="false"
					placeholder="phone"  focusColor="orange" ></tm-input>
			</tm-form-item>
			<tm-form-item required label="country" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.cardno" :transprent="true" :showBottomBotder="false"
					placeholder="country"></tm-input>
			</tm-form-item>
			<tm-form-item required label="city" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.addr" :transprent="true" :showBottomBotder="false"
					placeholder="city"></tm-input>
			</tm-form-item>	
			<tm-form-item required label="address" labelWidth="0">
				<tm-input v-model="entity.addrDetail" type="textarea" :transprent="true" :showBottomBotder="false"
					placeholder="detailed address" height="150"></tm-input>
			</tm-form-item>
			

			
			<tm-form-item :border="false">
				<view class=" flex flex-row">
					<view class="flex-1 mr-32">
						<tm-button form-type="submit" color="orange" label="save" followTheme="true" block></tm-button>
					</view>
				</view>
			</tm-form-item>
		</tm-form>

		
		
		<tm-message ref="msg" :lines="5"></tm-message>
	</tm-app>
</template>

<script lang="ts" setup>
	import { ref, nextTick } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { isPhone, isEmpty, isIdCard } from "@/tmui/tool/function/util";
	import tmMessage from "@/tmui/components/tm-message/tm-message.vue";
	import { getcode, savebs, queryCount, getBsByWxid } from '@/api/bs';
	import { saveJzZmSfz, saveJzFmSfz, getOcrDetail, saveTpImg } from '@/api/jz'
	import { schoolNameList } from '@/api/search'
	

	const msg = ref<InstanceType<typeof tmMessage> | null>(null)
	const placement = ref('top')
	const userid = ref('');
	const showflag = ref(true);
	const xyflag = ref(false);
	const list = ref([]);
	const zmlist = ref([]);
	const xsklist = ref([]);
	const zplist = ref([]);
	const selab = ref("获取验证码");
	const entity = ref({
		name: "",
		cardno: "",
		addr: "",
		subject: "",
		phone: "",
		addrDetail: "",
		wxid: "",
		zmsfz: "",
		fmsfz: "",
		xszImg: "",
		img: "",
		schoolId: "",
		remark: ""
	});
	const imgbase = ref("");
	const msgFlag = ref(false);
	const slist = ref([]);
	const showWin = ref(false);
	const pos = ref('bottom');

	onLoad(() => {
		userid.value = uni.getStorageSync("userid");
		// console.log('初始化程序加载数据！', userid.value);
		if (isEmpty(userid.value)) {
			uni.redirectTo({
				url: '/pages/auth/auth'
			})
		} else {
			entity.value.wxid = userid.value;
			// 进行获取用户是否填报过
			querybs();
		}
		// schoolList();
		// loadIsBs();
	})
	
	function loadXyContent() {
		uni.navigateTo({
			url: `/pages/news/xynews?id=10`
		})
	}
	const selCheckSchool = async(item:any) => {
		console.log(JSON.stringify(item));
		entity.value.school = item.name;
		entity.value.schoolId = item.id;
		showWin.value = false;
	}
	
	const selSchool = async() => {
		showWin.value = true;
	}
	
	const schoolList = async () => {
		const result = await schoolNameList();
		 // console.log(JSON.stringify(result));
		slist.value = result;
	}

	const zmtest = (item : any) => {
		let d = item.response;
		let isOk = true
		try {
			let p = JSON.parse(d)
			if (p?.code !== 0) {
				isOk = false;
			}
		} catch (e) {
			isOk = false;
		}

		return isOk;
	}
	// ---------------------上传身份证正面信息并获取基本信息----------------------------------
	const onZmStart = (item : any) => {
		imgToBase64(item.url);
		return true;
	}
	// 图片转base64方法
	const imgToBase64 = async (url : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				saveZmSfz();
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}
	// 身份证正面保存
	const saveZmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzZmSfz(param);
		entity.value.zmsfz = result.url;
		// 通过上传的身份证图片，识别身份证信息
		loadOcrDetail();
	}
	const loadOcrDetail = async () => {
		let param = { "url": entity.value.zmsfz };
		const result = await getOcrDetail(param);
		console.log(JSON.stringify(result));
		entity.value.cardno = result.msg.id;
		entity.value.name = result.msg.name;
	}

	// -----------------------身份证反面上传-------------------------------
	const onStart = (item : any) => {
		imgFmToBase64(item.url, '1');
		return true;
	}
	// 身份证反面保存
	const saveFmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzFmSfz(param);
		entity.value.fmsfz = result.url;
	}

	// -----------------------校园卡等图片上传-------------------------------
	const onXyStart = (item : any) => {
		imgFmToBase64(item.url, '2');
		return true;
	}
	const onTpStart = (item : any) => {
		imgFmToBase64(item.url, '3');
		return true;
	}
	// 身份证反面保存
	const saveonXyKImg = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzFmSfz(param);
		entity.value.xszImg = result.url;
	}
	
	const saveonTpImg = async() => { // ysxm
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveTpImg(param);
		entity.value.img = result.url;
	}








	// 图片转base64方法
	const imgFmToBase64 = async (url : string, status : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				if (status === '1') {
					saveFmSfz();
				}
				if (status === '2') {
					saveonXyKImg();
				}
				if (status === '3') {
					saveonTpImg();
				}
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}


	const loadIsBs = async () => {
		let param = { "wxid": userid.value }
		const result = await getBsByWxid(param);
		// console.log(result);
		if (!isEmpty(result.id)) {
			uni.setStorageSync("code", "0");
			msg.value.show({ model: 'success',text: '绑定成功' })
			uni.redirectTo({
				url: '/pages/index/my'
			})
		}
	}


	function allChange(e : any) {
		xyflag.value = e;
	}

	const querybs = async () => {
		let param = { "wxid": userid.value };
		const jg = await queryCount(param);
		// console.log("结果：：：", JSON.stringify(jg));
		entity.value = jg;
		
	}


	function confirm() {
		if (isEmpty(entity.value.name)) {
			msg.value.show({ model: 'error',text: 'name is not null!' })
			return false;
		}
		
		if (isEmpty(entity.value.phone)) {
			msg.value.show({ model: 'error',text: 'phone is not null!' })
			return false;
		}
		if (isEmpty(entity.value.cardno)) {
			msg.value.show({ model: 'error',text: 'country is not null!' })
			return false;
		}
		if (isEmpty(entity.value.addr)) {
			msg.value.show({ model: 'error',text: 'city is not null!' })
			return false;
		}
		if (isEmpty(entity.value.addrDetail)) {
			msg.value.show({ model: 'error',text: 'address is not null!' })
			return false;
		}
		savebangshou();
		return true;
	}




	const savebangshou = async () => {
		entity.value.wxid = userid.value;
		const result = await savebs(entity.value);
		console.log(result);
		if (result.code === "200") {
			uni.redirectTo({
				url: 'pages/index/my'
			})
		} else if (result.code === "400") {
			msg.value.show({ model: 'error',text: result.msg })
		}
	}


</script>

<style>

</style>